<!DOCTYPE html>
<html>
<title>Registration Page :: DIF233 - Unit 1 - Excercise 2</title>
<body>
	<?php
	
		function get_connection(){
			$file = fopen("config.txt","r+") or exit("Sorry not able to open the register file");
			$line = fgets($file);
			$value = explode(":", $line);
			$connection = mysqli_connect($value[0], $value[1], $value[2], $value[3]);
			
			if(mysqli_connect_errno($connection)){
				echo "unable to connect to test data base";
				exit("unable to connect to test data base");
			}else{
				return $connection;
			}
		}
		function update_password($connection, $id, $new_password){
			$update_details = "update user_credentials set password = '".$new_password."' where id = ".$id;
			echo $update_details;
			if(!mysqli_query($connection, $update_details)){
				echo "<h3>Failed to update due to : </h3>".mysqli_error($connection);
				header("Location: password_change.php?id=".$_POST["id"]);
				exit();
			}
		}
		function is_valid_password($connection, $id, $password){
			$get_details = "select user_name from user_credentials where id = ".$id." and password='".$password."'";
			echo $get_details;
			$result = mysqli_query($connection, $get_details);
			$count = 0;
			while($row = mysqli_fetch_array($result)){
				$count++;
			}
			return $count;
		}
		if(!empty($_POST["Update"])){
			$connection = get_connection();
			if(is_valid_password($connection, $_POST["id"], $_POST["current_passwd"])){
				update_password($connection, $_POST["id"], $_POST["new_passwd"]);
				header("Location: user.php?passwd=updated&id=".$_POST["id"]);
				exit();
			}else{
				echo "<h3>Current password is wrong</h3>";
				header("Location: password_change.php?id=".$_POST["id"]);
				exit();
			}
			mysqli_close($connection);
		}
	?>
<form method="post" name="change_pword" action="password_change.php?id=<?php echo $_GET['id']; ?>">

	<table style="border=0">
		<tr>
			<td>
				Current Password:
			</td>
			<td>
				<input type="password" name="current_passwd" value="" placeholder="Your Current Password" required />
			</td>
		</tr>
		<tr>
			<td>
				New Password:
			</td>
			<td>
				<input type="password" name="new_passwd" value="" placeholder="Your New Password" required />
			</td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" name="Update" value="Update" /></td>
		</tr>		
	</table>
	<input type="hidden" name="id" value=<?php echo empty($_GET["id"])?$_POST["id"]:$_GET["id"]?> />
</form>
</body>
</html>
